package com.hue.concurrent.day04;

import java.util.LinkedList;
import java.util.Queue;

/*
    异步模式之生产者消费者模式:
        使用消息队列来平衡生产者和消费者
 */
public class Demo01 {
    public static void main(String[] args) {
        MessageQueue queue = new MessageQueue(2);

//        new Thread(() -> {
//            while (true){
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                Message message = queue.get();
//                System.out.println("消费者消费一个:id=" + message.getId() + ",message=" + message.getMessage());
//            }
//        }).start();

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    try {
                        Thread.sleep(200*j);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Message message = new Message(j, "hello"+j);
                    queue.put(message);
                    System.out.println("生产者生产1个");
                }
            }).start();
        }
    }
}

class MessageQueue {
    private final int capacity;
    private final Queue<Message> queue = new LinkedList<>();

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    public Message get() {
        Message message = null;
        synchronized (queue) {
            while (queue.isEmpty()) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            message = queue.poll();
            queue.notifyAll();
        }
        return message;
    }

    public void put(Message message) {
        synchronized (queue) {
            while (queue.size() == capacity) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.add(message);
            queue.notifyAll();
        }
    }
}

final class Message {
    private int id;
    private Object message;

    public Message(int id, Object message) {
        this.id = id;
        this.message = message;
    }

    public int getId() {
        return id;
    }

    public Object getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", message=" + message +
                '}';
    }
}
